const app = getApp();


/**
 * wx.request封装
 * @param {String} url
 * @param {Object} data
 * @param {String} method
 */
const request = (url, data = {}, method = 'GET') => new Promise((resolve, reject) => {
  wx.request({
    url,
    data,
    method,
    header: {
      'Content-Type': 'application/json',
      "Authorization": 'Bearer '+ wx.getStorageSync('accessTokenData').accessToken
      // wxappkey: app.globalData.smartGateSession.key,
      // wxclientid: app.globalData.pwd, // 每次生命周期内携带相同的wxclientid，增加网关验证亲和性
    },
    success(res) {
      if (res.statusCode === 200) {
        // 写入缓存过期时间
        res.data.expire_time = Date.now() + app.globalData.data_Expire_Time;
        // 写缓存
        const stroageId = Object.values(data).join('');
        wx.setStorageSync(`${url}${stroageId}`, JSON.stringify(res.data));
        resolve(res.data);
      } else {
        reject(res.errMsg);
      }
    },
    fail(err) {
      reject(err);
    },
  });
});

const get = (url, data = {}) => request(url, data, 'GET');

const post = (url, data = {}) => request(url, data, 'POST');

const getUserInfo = () => new Promise((resolve, reject) => {
  wx.getUserInfo({
    withCredentials: true,
    success(res) {
      if (res.detail.errMsg === 'getUserInfo:ok') {
        resolve(res);
      } else {
        reject(res);
      }
    },
    fail(err) {
      reject(err);
    },
  });
});

module.exports = {
  get,
  post,
  getUserInfo,
};
